﻿
//var fieldList_barSortTools = "<a class=\"layui-btn layui-btn-primary layui-btn-xs\" lay-event=\"up\" ><i class=\"layui-icon layui-icon-up\" style=\"margin-right:1px;\"></i></a><a class=\"layui-btn layui-btn-primary layui-btn-xs \" lay-event=\"down\" style=\"margin-left:0px;\"><i class=\"layui-icon layui-icon-down\" style=\"margin-right:1px;\"></i></a>";
//var fieldList_barEditTools = "<a class=\"layui-btn layui-btn-xs\" lay-event=\"edit\" style=\"background-color:#3598dc;\"><i class=\"layui-icon layui-icon-edit\" style=\"margin-right:1px;\"></i></a><a class=\"layui-btn layui-btn-danger layui-btn-xs \" lay-event=\"del\" style=\"background-color:#e7505a; margin-left:0px;\"><i class=\"layui-icon layui-icon-delete\" style=\"margin-right:1px;\"></i></a>";
//var fieldList_barTopTools = "<a class=\"layui-btn layui-btn-sm\" lay-event=\"add\"><i class=\"layui-icon layui-icon-addition\"></i>新增</a><a class=\"layui-btn layui-btn-sm layui-btn-primary\" lay-event=\"clear\" ><i class=\"layui-icon layui-icon-delete\" ></i>清空</a>";



//列表字段
function init_FieldList() {
    var list_fieldlist = $("table[field_type=list]");
    $.each(list_fieldlist, function (i, e) {
        fieldList_layTable($(this).attr("field"));
    });
}


var fieldList_Json = {};
fieldList_Json.action = ""; //edit or add
fieldList_Json.name = ""; //字段名称
fieldList_Json.data = ""; //如果是编辑这里是编辑的数据
fieldList_Json.list = ""; //字段中有有什么字段
fieldList_Json.index = 0; //编辑的话 编辑的是第几个


function fieldList_setValue(fieldName, values) {
    $("#data_" + fieldName).html(values);
}

/**
 * 添加一行
 * @param obj tab对象
 */
function fieldList_addRow(obj) {

    this_id = fieldList_getTabId(obj);

    fieldList_Json.action = "add";
    fieldList_Json.name = this_id;
    fieldList_Json.list = fieldList_getFieldJson(this_id);

    //iframe层-父子操作
    layer.open({
        title: "增加数据",
        type: 2,
        area: ['1200px', '700px'],
        fixed: true, //不固定
        maxmin: false,
        resize: false,
        scrollbar: false,
        content: appConfig.adminPath + '/Page/layer/fieldlist.aspx?list=' + encodeURIComponent(JSON.stringify(fieldList_Json.list)),
        btn: [' 确 定 ', ' 取 消 '],
        yes: function (index, layero) {
            var cmodel = window.document.getElementById("layui-layer-iframe" + index).contentWindow.getcmodel();
            //拿到了添加的值
            //塞进JSON
            var res = $("#data_" + this_id).html();
            if (res == "") { res = "[]"; }
            res = JSON.parse(unescape(res));
            res.push(cmodel);
            //console.log(JSON.stringify("点击确定",res));
            $("#data_" + this_id).html(escape(JSON.stringify(res)));
            fieldList_renderTable(obj);
            layer.close(index);
        },
        btn2: function (index, layero) {
            //return false 开启可禁止点击该按钮关闭
        }
    });


    //var this_field = (obj.config.id).split('_')[1];

    //var res = $("#data_" + this_field).html();
    //console.log(res);
    //res = JSON.parse(res);

    //$.each(res, function (i, e) {
    //    if (i == 0) {
    //        res.push(res[i])
    //    }
    //});
    //$("#data_" + this_field).html(JSON.stringify(res));

    //fieldList_renderTable(obj);

    //layer.msg('我要添加数据');
}

/**
 * 清空当前表格的数据
 * @param obj layTab的操作对象
 */
function fieldList_clearRow(obj) {
    var this_id = fieldList_getTabId(obj);
    var this_data = $("#data_" + this_id).html();
    if (this_data == "" || this_data == "[]") {
        //console.log(obj);
        layer.msg('当前无数据可清空');
    }
    else {
        layer.confirm('确定清除当前所有行吗 ?', function (index) {
            $("#data_" + this_id).html("");
            fieldList_renderTable(obj);
            layer.close(index);
        });
    }
}


/**
 * 上排序
 * @param obj tab对象
 * @param index 当前行下标
 */
function fieldList_upSort(obj, index) {
    var this_data = fieldList_getDataJson(fieldList_getTabId(obj));
    var this_id = fieldList_getTabId(obj);
    if (index == 0) {
        layer.msg('已经最顶了');
    }
    else {
        this_data = fieldList_exchangeIndex(this_id, index, index - 1);
        $("#data_" + this_id).html(escape(JSON.stringify(this_data)));
        fieldList_renderTable(obj);
    }
}
/**
 * 下排序
 * @param obj tab对象
 * @param index 当前行下标
 */
function fieldList_downSort(obj, index) {
    var this_data = fieldList_getDataJson(fieldList_getTabId(obj));
    var this_id = fieldList_getTabId(obj);
    if (index == this_data.length - 1) {
        layer.msg('已经最底了');
    }
    else {
        this_data = fieldList_exchangeIndex(this_id, index, index + 1);
        $("#data_" + this_id).html(escape(JSON.stringify(this_data)));
        fieldList_renderTable(obj);
    }
}



//编辑行
function fieldList_editRow(obj, index) {
    console.log(obj);

    this_id = fieldList_getTabId(obj);

    fieldList_Json.action = "edit";
    fieldList_Json.name = this_id;
    fieldList_Json.list = fieldList_getFieldJson(this_id);

    fieldList_Json.data = fieldList_getDataJson(this_id)[index];
    fieldList_Json.index = index;

    //iframe层-父子操作
    layer.open({
        title: "编辑数据",
        type: 2,
        area: ['1200px', '700px'],
        fixed: true, //不固定
        maxmin: false,
        resize: false,
        scrollbar: false,
        content: appConfig.adminPath + '/Page/layer/fieldlist.aspx?list=' + encodeURIComponent(JSON.stringify(fieldList_Json.list)),
        btn: [' 确 定 ', ' 取 消 '],
        yes: function (index, layero) {
            var cmodel = window.document.getElementById("layui-layer-iframe" + index).contentWindow.getcmodel();
            //拿到了添加的值
            //替换JSON
            var res = $("#data_" + this_id).html();



            res = JSON.parse(unescape(res));
            res[fieldList_Json.index] = cmodel;
            $("#data_" + this_id).html(escape(JSON.stringify(res)));
            fieldList_renderTable(obj);
            layer.close(index);
        },
        btn2: function (index, layero) {
            //return false 开启可禁止点击该按钮关闭
        }
    });

}


/**
 *  删除行
 * @param obj laytab对象
 * @param index 当前行的下标
 */
function fieldList_delRow(obj, index) {
    layer.confirm('确定删除当前行吗?', function (i) {
        var this_id = fieldList_getTabId(obj);
        var this_data = $("#data_" + this_id).html();
        this_data = JSON.parse(unescape(this_data));
        this_data.splice(index, 1); //删除
        //console.log(this_data);
        $("#data_" + this_id).html(escape(JSON.stringify(this_data)));
        fieldList_renderTable(obj);
        layer.close(i);
    });
}


/**
 * 交换JSON的位置 , 完事返回交换好了JSON
 * @param id 字段名称
 * @param index 点击行的下标
 * @param toindex 目标行的下标
 */
function fieldList_exchangeIndex(id, index, toindex) {
    var this_data = fieldList_getDataJson(id);
    var _temp = this_data[toindex]; //缓存被挪移的对象
    this_data[toindex] = this_data[index];
    this_data[index] = _temp;
    return this_data;
}

/**
 * 更新表格
 * @param obj layTab的操作对象
 */
function fieldList_renderTable(obj) {
    var this_field = fieldList_getTabId(obj);
    fieldList_layTable(this_field);
}

/**
 * 获取表格ID 通过laytab的对象
 * @param obj layTab的操作对象
 */
function fieldList_getTabId(obj) {
    return (obj.config.id).split('_')[1];
}

/**
 * 获取列表字段的JSON
 * @param {any} fieldName 字段名称
 */
function fieldList_getDataJson(fieldName) {
    var this_id = fieldName;
    var this_data = $("#data_" + this_id).html();
    this_data = this_data == "" ? "[]" : unescape(this_data);
    this_data = JSON.parse(this_data);
    return this_data;
}

function fieldList_getFieldJson(fieldName) {
    var this_id = fieldName;
    var this_field = $("#field_" + this_id).html();
    this_field = JSON.parse(this_field);
    return this_field;
}





/**
 * 初始化表格
 * @param id 字段Id
 */
function fieldList_layTable(id) {
    var elem = "Field_" + id;

    var dataList = [];
    var datas = $("#data_" + id).html();
    datas = datas == "" ? "[]" : datas;

    //console.log("datas", datas);
   // console.log("unescape datas", unescape(datas));


    datas = JSON.parse(unescape(datas));
   // console.log("JSON", datas);

    $.each(datas, function (i, e) {
        for (var key in e) {
            if (e[key].toLowerCase().endsWith('.jpg')
                || e[key].toLowerCase().endsWith('.png')
                || e[key].toLowerCase().endsWith('.bmp')
                || e[key].toLowerCase().endsWith('.gif')
                || e[key].toLowerCase().endsWith('.jpeg')) {
                e[key] = "<img src='" + e[key] + "' />";
            }
        }
        dataList.push(e);
    });


    var colsList = [];
    var cols = $("#field_" + id).html();
    cols = JSON.parse(cols);

    $.each(cols, function (i, e) {
        colsList.push({ field: e.Field, title: e.Head, unresize: true });
    });
    colsList.push({ field: '_sort_', title: '排序', unresize: true, fixed: 'right', width: 90, align: 'center', toolbar: '#barSortTools' });
    colsList.push({ field: '_action_', title: '操作', unresize: true, fixed: 'right', width: 90, align: 'center', toolbar: '#barEditTools' });
    //colsList.push({ field: '_sort_', title: '排序', unresize: true, fixed: 'right', width: 90, align: 'center', toolbar: fieldList_barSortTools });
    //colsList.push({ field: '_action_', title: '操作', unresize: true, fixed: 'right', width: 90, align: 'center', toolbar: fieldList_barEditTools });

    layui.use('table', function () {

        var table = layui.table;

        var tableIns = table.render({
            elem: "#" + elem
            , limit: 100
            //, toolbar: fieldList_barTopTools
            , toolbar: '#barTopTools'
            , defaultToolbar: []
            , data: dataList
            , page: false //开启分页
            , cols: [colsList]
            , id: elem
        });

        table.on('toolbar(' + elem + ')', function (obj) {
            if (obj.event === 'add') {
                fieldList_addRow(tableIns);
            } else if (obj.event === 'clear') {
                fieldList_clearRow(tableIns);
            }
        });

        table.on('tool(' + elem + ')', function (obj) {
            //var data = obj.data;
            var $this = $(this);
            var tr = $this.parents('tr');
            var trIndex = tr.data('index');
            if (obj.event === 'edit') {
                fieldList_editRow(tableIns, trIndex);
            } else if (obj.event === 'del') {
                fieldList_delRow(tableIns, trIndex);
            } else if (obj.event === 'up') {
                fieldList_upSort(tableIns, trIndex);
            } else if (obj.event === 'down') {
                fieldList_downSort(tableIns, trIndex);
            }
        });

    });

}


init_FieldList();

